package view;

import java.awt.EventQueue;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.util.List;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import dao.questionTypeDao;
import entity.questions;
import util.StringUtils;

import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class restquestion extends JInternalFrame {
    private JTable questionTypeTable;
    private JTextField questionIdField;
    private JTextField correctAnswerField;
    private JTextField questionTextField;
    private JTextField optionAField;
    private JTextField optionBField;
    private JTextField optionCField;
    private JTextField optionDField;
    private JTextField searchField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    restquestion frame = new restquestion();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public restquestion() {
        setTitle("试题管理");
        setIconifiable(true);
        setClosable(true);
        setBounds(100, 100, 857, 549);
        
        JScrollPane scrollPane = new JScrollPane();
        
        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "表单操作", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        
        JLabel lblNewLabel_7 = new JLabel("题干关键字查询");
        
        searchField = new JTextField();
        searchField.setColumns(10);
        
        JButton btnSearch = new JButton("查询");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String keyword = searchField.getText().trim();
                System.out.println("界面层获取的关键字: " + keyword); // 调试输出
                
                // 确保调用的是正确的方法
                fillTableData(keyword);
            }
        });
        
        // 初始化表格
        questionTypeTable = new JTable();
        questionTypeTable.setModel(new DefaultTableModel(
            new Object[][] {},
            new String[] {
                "题目编号", "题干要求", "选项A", "选项B", "选项C", "选项D", "正确答案", "考试科目"
            }
        ));
        
        // 添加表格选择监听器
        questionTypeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    int selectedRow = questionTypeTable.getSelectedRow();
                    if (selectedRow >= 0) {
                        fillFormFields(selectedRow);
                    }
                }
            }
        });
        
        scrollPane.setViewportView(questionTypeTable);
        
        JLabel lblNewLabel = new JLabel("题目编号");
        
        questionIdField = new JTextField();
        questionIdField.setEditable(false);
        questionIdField.setColumns(10);
        
        JLabel lblNewLabel_1 = new JLabel("正确答案");
        
        correctAnswerField = new JTextField();
        correctAnswerField.setColumns(10);
        
        JLabel lblNewLabel_2 = new JLabel("题干要求");
        
        questionTextField = new JTextField();
        questionTextField.setColumns(10);
        
        JLabel lblNewLabel_3 = new JLabel("选项A");
        
        optionAField = new JTextField();
        optionAField.setColumns(10);
        
        JLabel lblNewLabel_4 = new JLabel("选项C");
        
        optionCField = new JTextField();
        optionCField.setColumns(10);
        
        JLabel lblNewLabel_5 = new JLabel("选项B");
        
        optionBField = new JTextField();
        optionBField.setColumns(10);
        
        JLabel lblNewLabel_6 = new JLabel("选项D");
        
        optionDField = new JTextField();
        optionDField.setColumns(10);
        
        JButton btnUpdate = new JButton("修改");
        btnUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateQuestion();
            }
        });
        
        JButton btnDelete = new JButton("删除");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                deleteQuestion();
            }
        });
        
        // 布局代码
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
            gl_panel.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(63)
                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                        .addComponent(lblNewLabel)
                        .addComponent(lblNewLabel_2)
                        .addComponent(lblNewLabel_3)
                        .addComponent(lblNewLabel_4))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                            .addComponent(questionIdField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(ComponentPlacement.RELATED, 155, Short.MAX_VALUE)
                            .addComponent(lblNewLabel_1)
                            .addPreferredGap(ComponentPlacement.RELATED)
                            .addComponent(correctAnswerField, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE)
                            .addGap(161))
                        .addGroup(gl_panel.createSequentialGroup()
                            .addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
                                .addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
                                    .addGap(10)
                                    .addComponent(questionTextField))
                                .addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
                                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
                                        .addGroup(gl_panel.createSequentialGroup()
                                            .addGap(9)
                                            .addComponent(btnUpdate))
                                        .addComponent(optionAField, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                                        .addComponent(optionCField))
                                    .addGap(34)
                                    .addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
                                        .addComponent(lblNewLabel_6)
                                        .addComponent(lblNewLabel_5))
                                    .addGap(18)
                                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
                                        .addComponent(optionDField)
                                        .addComponent(optionBField, GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))))
                            .addGap(88))))
                .addGroup(gl_panel.createSequentialGroup()
                    .addContainerGap(366, Short.MAX_VALUE)
                    .addComponent(btnDelete)
                    .addGap(169))
        );
        gl_panel.setVerticalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel)
                        .addComponent(questionIdField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblNewLabel_1)
                        .addComponent(correctAnswerField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(ComponentPlacement.UNRELATED)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel_2)
                        .addComponent(questionTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGap(18)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(optionBField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblNewLabel_5)
                        .addComponent(optionAField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblNewLabel_3))
                    .addGap(18)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(optionCField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(optionDField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblNewLabel_6)
                        .addComponent(lblNewLabel_4))
                    .addGap(18)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnDelete)
                        .addComponent(btnUpdate))
                    .addContainerGap(22, Short.MAX_VALUE))
        );
        panel.setLayout(gl_panel);
        
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(120)
                    .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                        .addComponent(panel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(scrollPane, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 590, GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(104, Short.MAX_VALUE))
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(209)
                    .addComponent(lblNewLabel_7)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(searchField, GroupLayout.PREFERRED_SIZE, 176, GroupLayout.PREFERRED_SIZE)
                    .addGap(32)
                    .addComponent(btnSearch)
                    .addContainerGap(243, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(44)
                    .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel_7)
                        .addComponent(searchField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnSearch))
                    .addGap(27)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 151, GroupLayout.PREFERRED_SIZE)
                    .addGap(36)
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 215, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(31, Short.MAX_VALUE))
        );
        getContentPane().setLayout(groupLayout);
        
        // 初始化时加载所有题目
        fillTableData("");
    }

    // 填充表格数据
    private void fillTableData(String keyword) {
        DefaultTableModel dtm = (DefaultTableModel) questionTypeTable.getModel();
        dtm.setRowCount(0); // 清空表格
        
        List<questions> questionList = questionTypeDao.getQuestionsByKeyword(keyword);
        
        for (questions q : questionList) {
            Vector<Object> row = new Vector<>();
            row.add(q.getId());
            row.add(q.getQuestion_text());
            row.add(q.getOption_a());
            row.add(q.getOption_b());
            row.add(q.getOption_c());
            row.add(q.getOption_d());
            row.add(q.getCorrect_answer());
            row.add(q.getSubject());
            dtm.addRow(row);
        }
    }


    // 填充表单字段
    private void fillFormFields(int selectedRow) {
        questionIdField.setText(questionTypeTable.getValueAt(selectedRow, 0).toString());
        questionTextField.setText(questionTypeTable.getValueAt(selectedRow, 1).toString());
        optionAField.setText(questionTypeTable.getValueAt(selectedRow, 2).toString());
        optionBField.setText(questionTypeTable.getValueAt(selectedRow, 3).toString());
        optionCField.setText(questionTypeTable.getValueAt(selectedRow, 4).toString());
        optionDField.setText(questionTypeTable.getValueAt(selectedRow, 5).toString());
        correctAnswerField.setText(questionTypeTable.getValueAt(selectedRow, 6).toString());
    }

    // 删除问题
    protected void deleteQuestion() {
        String typeId = questionIdField.getText();
        if(StringUtils.isEmpty(typeId)) {
            JOptionPane.showMessageDialog(this, "请选择要删除的题目");
            return;
        }
        
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除这道题目吗?", "确认删除", JOptionPane.YES_NO_OPTION);
        if(confirm == JOptionPane.YES_OPTION) {
            int rs = questionTypeDao.Delquestion(Integer.parseInt(typeId));
            if(rs == 1) {
                JOptionPane.showMessageDialog(this, "删除成功");
                fillTableData(searchField.getText()); // 刷新表格
                clearFormFields(); // 清空表单
            } else {
                JOptionPane.showMessageDialog(this, "删除失败，请稍后重试");
            }
        }
    }

    // 修改问题
    private void updateQuestion() {
        if (StringUtils.isEmpty(questionIdField.getText())) {
            JOptionPane.showMessageDialog(this, "请选择要修改的题目");
            return;
        }
        
        questions question = new questions();
        question.setId(Integer.parseInt(questionIdField.getText()));
        question.setQuestion_text(questionTextField.getText());
        question.setOption_a(optionAField.getText());
        question.setOption_b(optionBField.getText());
        question.setOption_c(optionCField.getText());
        question.setOption_d(optionDField.getText());
        question.setCorrect_answer(correctAnswerField.getText());
        
         //修改功能
         int result = questionTypeDao.updateQuestion(question);
         if (result > 0) {
             JOptionPane.showMessageDialog(this, "修改成功");
             fillTableData(searchField.getText());
         } else {
             JOptionPane.showMessageDialog(this, "修改失败");
         }
    }

    // 清空表单字段
    private void clearFormFields() {
        questionIdField.setText("");
        questionTextField.setText("");
        optionAField.setText("");
        optionBField.setText("");
        optionCField.setText("");
        optionDField.setText("");
        correctAnswerField.setText("");
    }
}